package org.firecloud.h5fun.controller.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.CommonConfig;
import org.firecloud.h5fun.model.CommonQuery;
import org.firecloud.h5fun.model.javabean.ApplicationBean;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 设置Application信息通过Ajax方法调用URL：ajax_set_application<br>
 * 必须登陆：false<br>
 * 必须管理：false<br>
 * 参数：<br>
 * id，必须，要设置信息的Application的ID<br>
 * data，必须，Application中的数据，json数据<br>
 * name，必须，Application的名字<br>
 * context，必须，Application的介绍内容<br>
 * 注：无<br>
 * @author fc
 */
public class AjaxSetApplicationInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		Connection connection = null;
		JSONObject json = null;
		try {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
			int applictionId = Integer.parseInt(req.getParameter("id"));
			CommonConfig config = (CommonConfig) req.getServletContext().getAttribute("commonConfig");
			connection = config.getConn();
			ApplicationBean application = CommonQuery.select_application(connection, applictionId);
			if (loginUser != null&&loginUser.getId() == application.getUserId()) {
				String data = req.getParameter("data");
				String name = req.getParameter("name");
				String context = req.getParameter("context");
				CommonQuery.update_application_info(connection, applictionId, name, context, data);
				json = new JSONObject();
				json.put("type", 0);
			} else {
				json = new JSONObject();
				json.put("type", -1);
				json.put("msg", "权限不足");
			}
		} catch (SQLException e) {
			json = new JSONObject();
			json.put("type", -2);
			json.put("msg", "查询错误");
			e.printStackTrace();
		} catch (Exception e) {
			json = new JSONObject();
			json.put("type", -3);
			json.put("msg", "未知错误");
			e.printStackTrace();
			Logger.getRootLogger().error(e);
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception e) {
					Logger.getRootLogger().error(e);
				}
			}
		}
		resp.getWriter().print(json);
	}
}
